#!/usr/bin/env python
import os
import cgi
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api import memcache

import simplejson
import functools
import logging

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import urlfetch

class GetCode(webapp.RequestHandler):
  @verify_xsrf_token
  def get(self):
    id = self.request.get('id')
    entry = db.get(db.Key(str(id)))
    self.response.headers['Content-Disposition'] = "attachment header"
    self.response.headers['Content-Type'] = "application/json; charset=utf-8"
    self.response.headers['X-Content-Type-Options'] = 'nosniff'
    if (entry.user == users.get_current_user()):
      self.response.out.write(entry.jscode)
    else:
      self.response.out.write('')

def getTypes(self):
  types = self.request.get('type')
  splitTypes = types.split('|')
  for i in splitTypes:
    if not apis.has_key(i):
      return False
  return types

def getExpanded(self):
  expanded = self.request.get('exp')
  if not apis.has_key(expanded):
    return False
  return expanded

class Main(webapp.RequestHandler):
  def getAPISampleSourceIncludes(self, types):
    apiSampleSources = []
    if types:
      types = types.split('|')
      for i in types:
        apiSampleSources.append(apis[i])
    else:
      theApis = sorted(apis.keys())
      for i in range(0, len(theApis)):
        if theApis[i] == 'language':
          apiSampleSources.insert(0, apis[theApis[i]])
        else:
          apiSampleSources.append(apis[theApis[i]])

    return apiSampleSources

  def head(self):
    self.response.out.write('')
  def get(self):
    apiTypes = getTypes(self)
    expanded = getExpanded(self)
    cgiArgsDict = {}
    self.template_values = {}

    # these next couple lines of code are stupid because of laziness.
    if apiTypes:
      cgiArgsDict["type"] = apiTypes
    if expanded:
      cgiArgsDict["exp"] = expanded
    cgiArgs = urllib.urlencode(cgiArgsDict)
    self.template_values = getTemplateValues(self, cgiArgs);
    if apiTypes:
      self.template_values['curAPITypes'] = apiTypes
    if expanded:
      self.template_values['expandedCategory'] = expanded

    # sample_srcs = self.getAPISampleSourceIncludes(apiTypes)
    if apiTypes:
      apiTypes = '?type=' + apiTypes
    else:
      apiTypes = ''
    sample_srcs = ['/studio/apis/ajax/playground/getTOC' + apiTypes]
    self.template_values['sample_srcs'] = sample_srcs
    # self.response.out.write(simplejson.dumps(a))
    if users.get_current_user():
      # savedCode is an array of code entries..
      savedCode = grabSavedCode(self, users.get_current_user())
      savedCodeArr = []
      if savedCode:
        for i in savedCode:
          savedCodeArr.append({
            'files': ['get?id=' + str(i.key())],
            'sampleName': cgi.escape(i.sampleName),
            'boilerplateLoc': i.boilerplateLoc,
            'tags': cgi.escape(i.tags),
            'id': str(i.key())
            })

        savedCodeObj = [
          {
            'category': 'Saved Code',
            'samples': savedCodeArr
          }
        ]
        self.template_values['usersSamplesJSON'] = simplejson.dumps(savedCodeObj);

    t = datetime.datetime.now()
    todayInSeconds = time.mktime(t.timetuple())
#    tomorrowInSeconds =  todayInSeconds + 86400
#    tomorrowFormatted = datetime.datetime.fromtimestamp(tomorrowInSeconds)
    todayFormatted = datetime.datetime.fromtimestamp(todayInSeconds)
#    tomorrowFormatted = tomorrowFormatted.strftime("%a, %d %b %Y %I:%M:%S")
    todayFormatted = todayFormatted.strftime("%a, %d %b %Y %I:%M:%S")

    # self.response.headers['Expires'] = todayFormatted + ' GMT'
    self.response.headers['Expires'] = "Fri, 01 Jan 1990 00:00:00 GMT"
    self.response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'

    path = os.path.join(os.path.dirname(__file__), 'studio/studio.html')
    self.response.out.write(template.render(path, self.template_values))


class GetTOC(webapp.RequestHandler):
  def getAllTOCs(self):
    the_response_script = ''
    theApis = sorted(apis.keys())
    for i in range(0, len(theApis)):
      file_full_path = os.path.join(os.path.dirname(__file__), apis[theApis[i]])
      the_file = open(file_full_path)
      if theApis[i] == 'language':
        the_response_script = the_file.read() + '\n' + the_response_script
      else:
        the_response_script += "\n" + the_file.read()
      the_file.close()
    return the_response_script
  def getTOCsByType(self, types):
    the_response_script = ''
    splitTypes = types.split('|')
    for i in splitTypes:
      if apis.has_key(i):
        the_file = open(apis[i])
        the_response_script += "\n" + the_file.read()
        the_file.close()
    return the_response_script

  def get(self):
    types = self.request.get('type')
    
    if not types:
      types = 'all'
    TOC = memcache.get('TOC:' + types)
    the_response_script = ""
    if TOC:
      the_response_script = TOC
    else:
      # We don't have it in memcache, we need to grab the files and put them in memcache
      if types == 'all':
        # just grab all
        the_response_script = self.getAllTOCs()
      else:
        # grab only what we need    
        the_response_script = self.getTOCsByType(types)
        if the_response_script == '':
          the_response_script = self.getAllTOCs()
      memcache.set('TOC:' + types, the_response_script, 600)
    self.response.headers['Expires'] = "Fri, 01 Jan 1990 00:00:00 GMT"
    self.response.headers['content-type'] = 'text/javascript'
    self.response.headers['cache-control'] = 'no-cache, no-store, max-age=0, must-revalidate'
    self.response.out.write(the_response_script)

def main():
  application = webapp.WSGIApplication([('/mma/', Main),
                                        ('/mma/get', GetCode),
                                        ('/mma/cacheCode', CacheCode),
                                        ('/mma/apis/ajax/', Main),
                                        ('/mma/apis/ajax/get', GetCode),
                                        ('/mma/apis/ajax/cacheCode', CacheCode),
                                        ('/mma/apis/ajax/getTOC', GetTOC),
                                        ('/mma/apis/ajax/ga_error', GaError)],
                                       debug=False)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
